import java.util.ArrayList;
import java.util.List;

/**
 * @author tmh
 * @date 2024/9/27 22:31
 * @description
 */
public class T39组合总和 {
    private List<List<Integer>> result = new ArrayList<>();
    private List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        dfs(candidates,0,target,list,0);
        return result;
    }

    private void dfs(int[] nums, int sum, int target, List<Integer> list,int index) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            result.add(new ArrayList<>(list));
        }
        for (int i = index; i < nums.length; i++) {
            sum += nums[i];
            list.add(nums[i]);
            dfs(nums, sum, target, list,i);
            sum -= nums[i];
            list.remove(list.size() - 1);
        }
    }
}
